<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>组件访问-子访问父(parent-root)</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>

  <body>
    <!--  $parent(子访问父)、$root(根组件) -->
    <div id="app">
      <h1>{{rootmessage}}</h1>
      <con></con>
    </div>
    <!-- 父组件 -->
    <template id="parent">
      <div>
        <h1>{{parentmessage}}</h1>
        <ccon></ccon>
      </div>
    </template>
    <!-- 子组件 -->
    <template id="son">
      <div>
        <h1>{{sonmessage}}</h1>
        <button @click="getparentmessage">获取父组件数据</button>
        <button @click="getrootmessage">获取根数据</button>
      </div>
    </template>
    <script>
      //创建Vue实例,得到 ViewModel
      var app = new Vue({
        el: "#app",
        data: {
          // 根数据
          rootmessage: "我是根message",
        },
        methods: {},
        // 注册父组件
        components: {
          con: {
            template: "#parent",
            data() {
              return {
                parentmessage: "我是父组件",
              };
            },
            // 注册子组件
            components: {
              ccon: {
                template: "#son",
                data() {
                  return {
                    sonmessage: "我是子组件",
                  };
                },
                methods: {
                  // 访问父组件
                  getparentmessage() {
                    console.log(this.$parent.parentmessage);
                  },
                  // 访问根组件
                  getrootmessage() {
                    console.log(this.$root.rootmessage);
                  },
                },
              },
            },
          },
        },
      });
    </script>
  </body>
</html>
